<template>
  <div class="app-container">
    <div v-if="show=='a'">
      <el-form :model="queryParams" ref="queryParams" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="表单名称" prop="topicName">
          <el-input
            v-model="queryParams.topicName"
            placeholder="请输入名称"
            clearable
            style="width: 240px;"
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
<!--        <el-form-item>-->
<!--          <el-select v-model="queryParams.status" placeholder="请选择状态" size="small">-->
<!--            <el-option-->
<!--              v-for="item in options"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change = getDateRange
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">添加</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="tables" v-loading="loading" :data="list"  @sort-change="handleSortChange">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="表单名称" align="center" prop="topicName" />
        <el-table-column label="创建日期" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布状态" align="center" prop="activityStatus" width="130">
          <template slot-scope="scope">
            <span>{{ scope.row.activityStatus === 0 ? '未发布' : '已发布' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否有效" align="center" prop="expireDate" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.expireDate">{{ $moment($moment(scope.row.expireDate).format('YYYY-MM-DD')).diff($moment($moment().format('YYYY-MM-DD')),'days') > 0 ? '有效' : '失效' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.activityStatus === 0"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document-copy"
              @click="handleCopy(scope.row)"
            >复制</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-tickets"
              @click="handlePublic(scope.row)"
            >{{scope.row.activityStatus == 0?'发布':'取消发布'}}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document-copy"
              v-clipboard:copy="`${url}?id=${scope.row.id}&topicName=${scope.row.topicName}&expireDate=${scope.row.expireDate}&status=${scope.row.activityStatus}`" v-clipboard:success="onCopy" v-clipboard:error="onError"
            >复制链接</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="dataView(scope.row)"
            >数据</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-full-screen"
              @click="ecode(`${url}?id=${scope.row.id}&topicName=${scope.row.topicName}`)"
            >生成二维码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <create-form v-if="show == 'b'" :form.sync="formContent" :formType="formType" :show.sync="show">
    </create-form>
    <el-dialog
      title="扫描填写表格"
      :visible.sync="dialogVisible"
      :before-close="closeCode"
      width="350px">
      <div class="ecode-box" ref="qrCodeDiv"></div>
      <span slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="closeCode">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { formList,formPublic,updateisDelete,formCopy } from "@/api/form.js";
import CreateForm from '@/views/tool/build/index'
import FormView from './formview'
import VueClipboard from 'vue-clipboard2'
import Vue from "vue"
import QRCode from 'qrcodejs2'
Vue.use(VueClipboard)
export default {
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [
        {topicName:'环保调查', creater:'wsl', operTime:new Date()}
      ],
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],

      options:[
        {value: 0,label: '未发布'},
        {value: 1,label: '已发布'}
      ],
      // 表单参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      formDetail:{},
      show:'a',
      formType:'',
      formContent:{},
      url:'',
      dialogVisible:false
    };
  },
  components:{CreateForm,FormView},
  mounted() {
    this.getList();
    //let temp = this.url = `http://${location.href.split('/')[2]}/#/detail`
    this.url = `http://${window.location.host}/dtbd/#/detail`
  },
  methods: {
    getList() {
      formList(this.queryParams).then( response => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    handleAdd(){
      this.show = 'b'
      this.formType = 'add'
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.$router.push({path:'detail',query:{id:row.id,topicName:row.topicName,type:'view'}})
    },
    handleEdit(row){
      this.formContent = row
      this.formType = 'edit'
      this.show = 'b'
    },
    handlePublic(row){
      this.$confirm(`${row.activityStatus == 0?'确定要发布吗':'确定取消发布吗'}`, '请确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success',
        callback: action => {
          if (action === 'confirm') {
            formPublic({id:row.id,activityStatus:row.activityStatus == 0?1:0}).then(()=>{
              this.$message.success(row.activityStatus == 0?'发布成功':'消取发布')
              this.getList();
            })
          }
          else {

          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除该表单？').then(function() {
        return updateisDelete({id:row.id,isDelete:1});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleCopy(row){
      this.$modal.confirm('是否确认复制该表单？').then(function() {
        return formCopy({id:row.id});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("复制成功");
      }).catch(() => {});
    },
    /** 清空按钮操作 */
    onCopy(e) {
      this.$message.success("链接已复制到剪切板！")
    },
    onError (e) {
      this.$message.error("抱歉，复制失败！")
    },
    dataView(row) {
      this.$router.push({path:'datalist',query:{topicId:row.id,topicName:row.topicName,type:'view'}})
    },
    ecode(url){
      this.dialogVisible = true
      this.$nextTick(()=>{
        new QRCode(this.$refs.qrCodeDiv, {
          text: url,
          width: 200,
          height: 200,
          colorDark: "#333333", //二维码颜色
          colorLight: "#ffffff", //二维码背景色
          correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
        })
      })
    },
    closeCode(){
      this.$refs.qrCodeDiv.innerHTML = ''
      this.dialogVisible = false
    },
    getDateRange(val){
      if(val){
        this.queryParams.createTimeBegin = val[0]+' 00:00:00'
        this.queryParams.createTimeEnd = val[1]+' 59:59:59'
      }else{
        this.queryParams.createTimeBegin = ''
        this.queryParams.createTimeEnd = ''
      }
    }
  },
  watch:{
    show(val){
      this.getList();
    }
  }
};
</script>
<style scoped>
.ecode-box{
  display: flex;
  justify-content: center;
}
</style>

